package com.keeping.aiimagery.controller;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.keeping.aiimagery.entity.Storage;
import com.keeping.aiimagery.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;

@RestController
public class StorageController {
    @Autowired(required = false)
    private StorageService storageService;

    //获取图片
    @GetMapping("/imageGet")
    public String imageGet( String userAccount){
            List<Storage> storages = storageService.selectAll(userAccount);
        List<HashMap<String,String>> images = new ArrayList<>();
        for (Storage storage:storages) {
            String imagePath = storage.getImagePath();

            File file = new File(imagePath);
//            images.put(imagePath,Base64.encode(file));
            if(file.exists()){
                images.add(new HashMap<String,String>(){{put("imagePath",imagePath);put("imageBase64",Base64.encode(file));}});
            }else continue;
        }
//        HashMap<String, List<String>> image = new HashMap<>();
//        image.put("images",images);
//            System.out.println(images);
        return JSONUtil.toJsonStr(images);
    }

    //存储图片
    @PostMapping("/imageStorage")
    public String imageStorage(@RequestBody Map data) {
        String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");;
        String userAccount = (String) data.get("userAccount");
        String type = (String) data.get("type");//key,generate
        String image = (String) data.get("image");
        String filePath = "image/" + userAccount + "/" +type + "/" + uuid + ".jpg";
        String result = "存储成功";
        try {
            File file = FileUtil.newFile(filePath);
            byte[] imageBytes = Base64Decoder.decode(image);
            FileUtil.writeBytes(imageBytes,file);
//            FileUtil.writeUtf8String(image, file);
            storageService.insert(userAccount,filePath);
        } catch (Exception e) {
            result = "存储失败";
            throw new RuntimeException(e);
        }
        System.out.println(result);
        return result;
    }

    //不做删除处理
//    @GetMapping("/imageDelete")
//    public String imageDelete(String ){
//
//    }

}

